<template>
  <div class="app-container">

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="学年" prop="schoolYear">
        <el-select v-model="queryParams.schoolYear" placeholder="请选择学年" clearable :style="{ width: '100%' }">
          <el-option v-for="(item, index) in schoolYearOptions" :key="index" :label="item.schoolYear"
            :value="item.schoolYear" :disabled="item.disabled"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="班级信息" prop="gradeName">
        <el-input v-model="queryParams.gradeName" placeholder="请输入班级名称或班级代码" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="辅导员" prop="nickName">
        <el-input v-model="queryParams.nickName" placeholder="请输入辅导员名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-tabs v-model="activeName" type="card" @tab-click="handleTabs">
      <el-tab-pane label="已分配班级" name="yfp">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleplUpdata"
              v-hasPermi="['backend:instructor:add']">批量修改分配</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
              v-hasPermi="['backend:instructor:export']">导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="instructorList" @selection-change="handleSelectionChange"
          :span-method="objectSpanMethod" border>
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="辅导员" align="center" prop="nickName" />
          <el-table-column label="学年" align="center" prop="schoolYear" />
          <el-table-column label="班级代码" align="center" prop="gradeCode" />
          <el-table-column label="班级名称" align="center" prop="gradeName" />
          <el-table-column label="是否毕业" align="center" prop="isFinishSchool">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.isFinishSchool == 1">未毕业</el-tag>
              <el-tag type="danger" v-else>已毕业</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['backend:instructor:edit']">修改分配</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                v-hasPermi="['backend:instructor:remove']">删除分配</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" style="margin-bottom:20px" />

        <!-- 批量修改辅导员 -->
        <el-dialog :title="title" :visible.sync="openplupdata" width="1200px" append-to-body>
          <el-form style="overflow-y:scroll;max-height:80vh;padding-right: 30px;">
            <el-card class="box-card" v-for="(item, index) in plUpdata" :key="index" style="margin-bottom:5px">
              <div slot="header" class="clearfix">
                <span>{{ "班级名称：" + item.gradeName }}</span>
              </div>
              <div class="text item">{{ "学年:" + item.schoolYear }}</div>
              <div class="text item">{{ "班级代码:" + item.gradeCode }}</div>
              <div class="text item">{{ "是否毕业:" }}
                <el-tag v-if="item.isFinishSchool == 1">未毕业</el-tag>
                <el-tag type="danger" v-else>已毕业</el-tag>
              </div>
              <div class="text item">{{ "原辅导员:" + item.nickName }}</div>
            </el-card>
          </el-form>

          <hr color="lightgray" style="margin-top:20px" />

          <el-form ref="form" :model="formUpdata" :rules="rulesUpdata" label-width="80px" style="margin-bottom:20px">
            <el-form-item label="新辅导员" prop="instructor">
              <el-select v-model="formUpdata.instructor" placeholder="请选择辅导员" clearable filterable
                :style="{ width: '100%' }">
                <el-option v-for="(item, index) in userList" :key="item.userId" :label="item.nickName"
                  :value="item.userId" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
          </el-form>

          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitplForm">确 定</el-button>
            <el-button @click="cancelplUpdata">取 消</el-button>
          </div>
        </el-dialog>
      </el-tab-pane>

      <!-- 未分配班级 -->
      <el-tab-pane label="未分配班级" name="wfp">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleplAdd"
              v-hasPermi="['backend:instructor:add']">批量分配</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="instructorList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="辅导员" align="center" prop="nickName">
            <template slot-scope="scope">
              <span>{{ scope.row.nickName == null ? "未分配" : scope.row.nickName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="学年" align="center" prop="schoolYear" />
          <el-table-column label="班级代码" align="center" prop="gradeCode" />
          <el-table-column label="班级名称" align="center" prop="gradeName" />
          <el-table-column label="是否毕业" align="center" prop="isFinishSchool">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.isFinishSchool == 1">未毕业</el-tag>
              <el-tag type="danger" v-else>已毕业</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['backend:instructor:edit']">分配辅导员</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
          @pagination="getList" style="margin-bottom:20px" />

        <!-- 批量设置辅导员 -->
        <el-dialog :title="title" :visible.sync="openplInset" width="1200px" append-to-body>
          <el-form style="overflow-y:scroll;max-height:80vh;padding-right: 30px;">
            <el-card class="box-card" v-for="(item, index) in plUpdata" :key="index" style="margin-bottom:5px">
              <div slot="header" class="clearfix">
                <span>{{ "班级名称：" + item.gradeName }}</span>
              </div>
              <div class="text item">{{ "学年:" + item.schoolYear }}</div>
              <div class="text item">{{ "班级代码:" + item.gradeCode }}</div>
              <div class="text item">{{ "是否毕业:" }}
                <el-tag v-if="item.isFinishSchool == 1">未毕业</el-tag>
                <el-tag type="danger" v-else>已毕业</el-tag>
              </div>
            </el-card>
          </el-form>

          <hr color="lightgray" style="margin-top:20px" />

          <el-form ref="form" :model="formUpdata" :rules="rulesUpdata" label-width="80px" style="margin-bottom:20px">
            <el-form-item label="新辅导员" prop="instructor">
              <el-select v-model="formUpdata.instructor" placeholder="请选择辅导员" clearable filterable
                :style="{ width: '100%' }">
                <el-option v-for="(item, index) in userList" :key="item.userId" :label="item.nickName"
                  :value="item.userId" :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
          </el-form>

          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitplInsetForm">确 定</el-button>
            <el-button @click="cancelplInset">取 消</el-button>
          </div>
        </el-dialog>
      </el-tab-pane>

      <!-- 添加或修改辅导员对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="学年" prop="schoolYear">
            <el-input v-model="form.schoolYear" placeholder="" disabled="disabled" />
          </el-form-item>

          <el-form-item label="班级代码" prop="gradeCode">
            <el-input v-model="form.gradeCode" placeholder="" disabled="disabled" />
          </el-form-item>

          <el-form-item label="班级名称" prop="gradeName">
            <el-input v-model="form.gradeName" placeholder="" disabled="disabled" />
          </el-form-item>

          <el-form-item label="是否毕业" prop="gradeName">
            <el-tag v-if="form.isFinishSchool == 1">未毕业</el-tag>
            <el-tag type="danger" v-else>已毕业</el-tag>
          </el-form-item>

          <el-form-item label="辅导员" prop="instructor">
            <el-select v-model="form.instructor" placeholder="请选择辅导员" clearable filterable :style="{ width: '100%' }">
              <el-option v-for="(item, index) in userList" :key="item.userId" :label="item.nickName" :value="item.userId"
                :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </el-tabs>



  </div>
</template>

<script>
import { listInstructor, getInstructor, delInstructor, addInstructor, updateInstructo, updateMoreInstructor, addMoreInstructor } from "@/api/backend/instructor";
import { allListUser } from "@/api/system/user";
import { listSchoolYearList } from "@/api/backend/semester";

export default {
  name: "Instructor",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      gradeId: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 辅导员表格数据
      instructorList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openplupdata: false,
      openplInset: false,
      //设置默认打开页面
      activeName: 'yfp',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        gradeName: null,
        nickName: null,
        schoolYear: null,
        isNull: 1,
      },
      // 表单参数
      form: {},
      userList: {},
      plUpdata: {},
      formUpdata: {},
      // 表单校验
      rules: {
        instructor: [{
          required: true,
          message: '请选择辅导员',
          trigger: 'change'
        }],
      },
      rulesUpdata: {
        instructor: [{
          required: true,
          message: '请选择辅导员',
          trigger: 'change'
        }],
      },
      schoolYearOptions: [],
      //data里面需要合并的项以及对应的spanArr和pos
      mergerItems: [
        {
          columnIndex: 1,
          spanArr: [],
          pos: 0,
          prop: 'nickName',
          parent: []
        },
        {
          columnIndex: 2,
          spanArr: [],
          pos: 0,
          prop: 'schoolYear',
          parent: ['nickName']
        }]
    };
  },
  created() {
    this.getList();
    this.getAdminUser();
    this.getSchoolYearList();
  },
  methods: {
    getSchoolYearList() {
      listSchoolYearList().then(response => {
        this.schoolYearOptions = response.rows;
      });
    },
    /** 监听选项卡 */
    handleTabs(tab, event) {
      if (tab.name == 'yfp') {
        this.queryParams.isNull = 1;
      } else {
        this.queryParams.isNull = 2;
      }
      this.getList();
    },
    /** */
    getAdminUser() {
      allListUser().then(response => {
        this.userList = response.rows;
      });
    },
    /** 查询辅导员列表 */
    getList() {
      this.loading = true;
      listInstructor(this.queryParams).then(response => {
        this.instructorList = response.rows;
        this.getSpanArr(this.instructorList, this.mergerItems)
        this.total = response.total;
        this.loading = false;
      });
    },
    getSpanArr(data, array) {//循环数据处理
      for (let n = 0; n < array.length; n++) {
        array[n].spanArr = []//数据清空(重新调此方法的时候需要清空上一次的数据)
        for (let i = 0; i < data.length; i++) {
          if (i === 0) {
            array[n].spanArr.push(1);
            array[n].pos = 0;
          } else {

            // 判断当前元素与上一个元素是否相同
            let flag = true;
            for (let j = 0; j < array[n].parent.length; j++) {

              if (data[i][array[n].parent[j]] !== data[i - 1][array[n].parent[j]]) {
                flag = false;
                break;
              }
            }
            if (flag && data[i][array[n].prop] === data[i - 1][array[n].prop]) {
              array[n].spanArr[array[n].pos] += 1;
              array[n].spanArr.push(0);
            } else {
              array[n].spanArr.push(1);
              array[n].pos = i;
            }
          }
        }
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1 || columnIndex === 2) {//这里判断第几列需要合并
        let item = this.mergerItems.find(item => item.columnIndex === columnIndex)
        const _row = item.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col,
        }
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        instructor: null,
        gradeId: null,
        operator: null
      };
      this.resetForm("form");
    },
    // 表单重置
    reset2() {
      this.formUpdata = {
        id: null,
        instructor: null,
        gradeId: null,
        operator: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.gradeId = selection.map(item => item.bjyId)
      this.plUpdata = selection;
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加辅导员";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form = JSON.parse(JSON.stringify(row));;
      this.open = true;
      this.title = "修改辅导员";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            var UpdataData = {
              id: this.form.id,
              instructor: this.form.instructor,
            }
            updateInstructor(UpdataData).then(response => {
              this.$modal.msgSuccess("修改辅导员成功！");
              this.open = false;
              this.getList();
            });
          } else {
            var InsetData = {
              instructor: this.form.instructor,
              gradeId: this.form.bjyId
            }
            addInstructor(InsetData).then(response => {
              this.$modal.msgSuccess("分配辅导员成功！");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除班级名称为为"' + row.gradeName + '"的数据项？').then(function () {
        return delInstructor(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('backend/instructor/export', {
        ...this.queryParams
      }, `辅导员班级数据${new Date().getTime()}.xlsx`)
    },
    /** 批量修改分配 */
    handleplUpdata() {
      if (this.ids.length != 0) {
        this.title = "批量修改辅导员";
        this.openplupdata = true;
      } else {
        this.$message({
          message: '请选择至少1条数据！',
          type: 'warning'
        });
      }

    },
    /** 取消批量修改 */
    cancelplUpdata() {
      this.openplupdata = false;
      this.reset2();
    },
    /** 批量修改辅导员 */
    submitplForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          updateMoreInstructor(this.ids, this.formUpdata.instructor);
          this.getList();
          this.openplupdata = false;
          this.$modal.msgSuccess("修改班级辅导员成功！");
          this.reset2();
        }
      });
    },
    /** 批量分配 */
    handleplAdd() {
      if (this.ids.length != 0) {
        this.title = "批量设置辅导员";
        this.openplInset = true;
      } else {
        this.$message({
          message: '请选择至少1条数据！',
          type: 'warning'
        });
      }
    },
    cancelplInset() {
      this.openplInset = false;
      this.reset2();
    },
    //批量设置辅导员
    submitplInsetForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          addMoreInstructor(this.gradeId, this.formUpdata.instructor);
          this.getList();
          this.openplInset = false;
          this.$modal.msgSuccess("设置辅导员成功！");
          this.reset2();
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.box-card {
  width: 100%;
}
</style>
